<template>
  <div>
    <div class="main-content">
      <h3 class="club-name">
        <el-link class="club-link" type="danger" @click="navigateToClub(selectedClub.clubId)">{{ selectedClub.clubName
          }}</el-link>
        <link href="https://fonts.googleapis.com/css2?family=ZCOOL+KuaiLe&display=swap" rel="stylesheet">
      </h3>
      <el-divider border-style="dashed" />
      <!-- 修改社团信息功能 -->
      <el-button size="large" class="btn-join-approval" plain @click="showJoinApproval">审核人员加入</el-button>
      <el-button size="large" class="btn-admin-manager" plain @click="showAdminManager">修改社团管理员</el-button>
      <el-button size="large" class="btn-edit-info" plain @click="editClubInfo">修改社团信息</el-button>
      <el-button size="large" class="btn-edit-logo" plain @click="editClubLogo">修改社团Logo</el-button>
      <el-button size="large" class="btn-disband-club" plain @click="confirmDeleteClub">解散社团</el-button>

      <el-divider border-style="dashed" />

      <!-- 修改社团信息对话框 -->
      <el-dialog title="修改社团信息" v-model="editClubDialogVisible" width="50%" :before-close="handleClose">
        <el-form :model="clubInfoForm" :rules="rules" label-width="120px">
          <el-form-item label="介绍" prop="clubDescription">
            <el-input type="textarea" v-model="clubInfoForm.clubDescription"></el-input>
          </el-form-item>
          <el-form-item label="类型" prop="category">
            <el-select v-model="clubInfoForm.category" placeholder="请选择">
              <el-option label="学科技术类" value="学科技术类"></el-option>
              <el-option label="文艺体育类" value="文艺体育类"></el-option>
              <el-option label="公益服务类" value="公益服务类"></el-option>
              <el-option label="职业发展类" value="职业发展类"></el-option>
              <el-option label="国际交流类" value="国际交流类"></el-option>
              <el-option label="创新创业类" value="创新创业类"></el-option>
              <el-option label="娱乐休闲类" value="娱乐休闲类"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="社区开放范围" prop="postPublicScope">
            <el-select v-model="clubInfoForm.postPublicScope" placeholder="请选择">
              <el-option label="全部人员可见" value="用户可见"></el-option>
              <el-option label="社内人员可见" value="成员可见"></el-option>
              <el-option label="社内管理人员可见" value="管理员可见"></el-option>
              <el-option label="隐藏" value="已隐藏"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="开放程度" prop="postPublicScope">
            <el-select v-model="clubInfoForm.clubStatus" placeholder="请选择">
              <el-option label="开放" value="开放中"></el-option>
              <el-option label="限制加入" value="限制加入"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="加入条件" prop="requirements">
            <el-input v-model="clubInfoForm.requirements"></el-input>
          </el-form-item>
        </el-form>
        <div class="dialog-footer">
          <el-button @click="editClubDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveClubInfo">保存</el-button>
        </div>
      </el-dialog>

      <!-- 修改社团Logo对话框 -->
      <el-dialog title="修改社团Logo" center align-center v-model="editLogoDialogVisible" width="30%"
        :before-close="handleClose">
        <el-form label-width="120px">
          <el-form-item prop="clubLogo">
            <!-- <input type="file" @change="handleFileChange" /> -->

            <el-upload action="#" list-type="picture-card" :show-file-list="false" @change="handleLogoChange"
              auto-upload="false" limit="1">
              <img v-if="imageUrl" :src="imageUrl" style="width: 100%;" />
              <el-icon v-else>
                <Plus />
              </el-icon>
            </el-upload>
          </el-form-item>
        </el-form>

        <template #footer>
          <div class="dialog-footer">
            <el-button @click="clearUploadLogo">取消</el-button>
            <el-button type="primary" @click="uploadLogo">上传</el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 内容显示控制 -->
      <div v-if="activeView === 'adminManager'">
        <el-text class="mx-1" type="danger">修改社团管理员</el-text>
        <el-table :data="members" stripe style="width: 100%">
          <el-table-column prop="studentId" label="学号"></el-table-column>
          <el-table-column prop="name" label="姓名"></el-table-column>
          <el-table-column prop="clubPosition" label="职位">
            <template v-slot="scope">
              <el-select v-model="scope.row.clubPosition" @change="handlePositionChange(scope.row)"
                :disabled="scope.row.clubPosition === '一把手'">
                <el-option label="普通成员" value="普通成员"></el-option>
                <el-option label="二把手" value="二把手"></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template v-slot="scope">
              <el-button v-if="scope.row.member" type="danger" size="mini"
                @click="removeMember(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div v-if="activeView === 'joinApproval'">
        <el-text class="mx-1" type="danger">审核人员加入</el-text>
        <el-table :data="applicationList">
          <el-table-column prop="name" label="姓名"></el-table-column>
          <el-table-column prop="applyTime" label="申请时间"></el-table-column>
          <el-table-column label="操作">
            <template v-slot="scope">
              <el-button size="mini" type="primary" @click="approveJoinRequest(scope.row.applicationId)">批准</el-button>
              <el-button size="mini" type="danger" @click="rejectJoinRequest(scope.row.applicationId)">驳回</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import { ElLoading, ElMessage, ElMessageBox, ElNotification } from "element-plus";
import {Plus} from "@element-plus/icons-vue";

export default {
  name: "LeaderBottomRightComponent",
  props: {
    selectedClub: {
      type: Object,
      required: true,
    },
  },
  components: {
    Plus
  },
  data() {
    return {
      currentUserPosition: "",
      editClubDialogVisible: false,
      editLogoDialogVisible: false,
      clubInfoForm: {
        clubId: this.selectedClub.clubId,
        postPublicScope: this.selectedClub.postPublicScope,
        requirements: this.selectedClub.requirements,
        clubDescription: this.selectedClub.clubDescription,
        category: this.selectedClub.category,
        clubStatus:this.selectedClub.clubStatus
      },
      members: [], // 成员列表
      applicationList: [],
      activeView: 'adminManager',
      imageUrl:null
    };
  },
  created() {
    this.fetchApplicationList();
    this.fetchMembers(); // 初始化时获取成员信息
  },

  methods: {
    showAdminManager() {
      this.activeView = 'adminManager';
    },
    showJoinApproval() {
      this.activeView = 'joinApproval';
    },
    navigateToClub(clubId) {
      this.$router.push({ name: "ClubDetail", query: { clubId: clubId } });
    },
    editClubInfo() {
      this.editClubDialogVisible = true;
    },
    editClubLogo() {
      this.editLogoDialogVisible = true;
    },
    handleFileChange(event) {
      const file = event.target.files[0];
      this.clubInfoForm.logo = file;
    },
    handleLogoChange(file, fileList) {

      // 修改社团logo，改进版
      if (fileList.length > 0) {
        const reader = new FileReader();
        reader.onload = () => {
          this.imageUrl = reader.result;
        };
        reader.readAsDataURL(file.raw);
        this.clubInfoForm.logo = file.raw;
      }
    },
    clearUploadLogo() {
      // 清空上传的图片
      this.editLogoDialogVisible = false
      this.imageUrl = null;
      this.clubInfoForm.logo = null;
    },
    async uploadLogo() {
      // 上传图片
      if (!this.clubInfoForm.logo) {
        ElMessage.error('请选择图片');
        return;
      }

      const isLoading = ElLoading.service({
        lock: true,
        text: '上传中...',
        background: 'rgba(0, 0, 0, 0.7)',
      });

      const formData = new FormData();
      formData.append("logo", this.clubInfoForm.logo);
      formData.append("clubId", this.clubInfoForm.clubId);
      try {
        const response = await axios.put("/club/changeLogo", formData);
        if (response.data.code === 0) {
          this.$message.success("Logo上传成功");
          this.clearUploadLogo();
        } else {
          this.$message.error(response.data.message || "Logo上传失败");
        }
      } catch (error) {
        console.error("Error uploading logo:", error);
        this.$message.error("Logo上传失败");
      }

      isLoading.close();
    },
    async saveClubInfo() {
      const isLoading = ElLoading.service({
        lock: true,
        text: '保存中...',
        background: 'rgba(0, 0, 0, 0.7)',
      });

      try {
        const response = await axios.put(
          "/club/updateClubInfo",
          this.clubInfoForm
        );
        if (response.data.code === 0) {
          this.$message.success("社团信息保存成功");
          this.editClubDialogVisible = false;
        } else {
          // this.$message.error("社团信息保存失败");

          ElNotification({
            title: '社团信息修改失败',
            message: response.data.message || "未知错误",
            type: 'error',
            dangerouslyUseHTMLString: true,
          })
        }
      } catch (error) {
        console.error("Error saving club info:", error);
        this.$message.error("社团信息保存失败");
      }

      isLoading.close();
    },
    async confirmDeleteClub() {
      try {
        await ElMessageBox.confirm(
          "您确定要解散社团吗？此操作将无法恢复。",
          "警告",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "info",
          }
        );
        this.confirmDeleteClub2();
      } catch (error) {
        // 点击取消
      }
    },
    async confirmDeleteClub2() {
      try {
        await ElMessageBox.confirm(
          "您确定确定要解散社团吗？此操作将无法恢复。",
          "警告",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        );
        this.confirmDeleteClub3();
      } catch (error) {
        // 点击取消
      }
    },
    async confirmDeleteClub3() {
      try {
        await ElMessageBox.confirm(
          "您确定确定确确定定要解散社团吗？此操作将无法恢复。",
          "警告",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "error",
          }
        );
        this.deleteClub();
      } catch (error) {
        // 点击取消
      }
    },
    async deleteClub() {
      const formData = new FormData();
      formData.append("clubId", this.clubInfoForm.clubId);
      try {
        const response = await axios.post("/club/deleteClub", formData);
        if (response.data.code === 0) {
          this.$message.success("社团解散成功");
          this.$emit("switch-to-management");
        } else {
          this.$message.error("社团解散失败");
        }
      } catch (error) {
        console.error("Error deleting club:", error);
        this.$message.error("社团解散失败");
      }
    },
    handleClose(done) {
      this.imageUrl = null;
      this.clubInfoForm.logo = null;
      done(); // 关闭对话框
    },
    async fetchMembers() {
      try {
        const response = await axios.get("/participation/clubMemberList", {
          params: { clubId: this.clubInfoForm.clubId },
        });
        if (response.data.code === 0) {
          console.log(1);
          this.members = response.data.data.map((member) => ({
            ...member,
            member: member.clubPosition === "普通成员",
            isLeader: member.clubPosition === "一把手",
          }));
        }
      } catch (error) {
        console.error("Error fetching members:", error);
      }
    },
    async handlePositionChange(member) {
      try {
        let response;
        if (member.isLeader) {
          ElMessage.warning("无法调整");
          return;
        }

        if (member.clubPosition === "二把手") {
          response = await axios.post("/club/memberToSecondLeader", null, {
            params: {
              clubId: this.clubInfoForm.clubId,
              memberId: member.studentId,
            },
          });
        } else {
          response = await axios.post("/club/secondLeaderToMember", null, {
            params: {
              clubId: this.clubInfoForm.clubId,
              memberId: member.studentId,
            },
          });
        }
        if (response.data.code !== 0) {
          this.$message.error("职务调整失败");
        }else{
          ElMessage.success("职务调整成功");
        }
      } catch (error) {
        console.error("Error changing position:", error);
        this.$message.error("职务调整失败");
      }
    },

    async removeMember(member) {
      ElMessageBox.confirm("您确定要请出该成员吗?", "确认", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          if (!member.isLeader) {
            try {
              const response = await axios.post("/club/kick", null, {
                params: {
                  userId: member.studentId,
                  clubId: this.clubInfoForm.clubId,
                },
              });
              if (response.data.code === 0) {
                this.members = this.members.filter(
                  (m) => m.studentId !== member.studentId
                );
                this.$message.success("成员删除成功");
              } else {
                this.$message.error("成员删除失败");
              }
            } catch (error) {
              console.error("Error removing member:", error);
              this.$message.error("成员删除失败");
            }
          }
        })
        .catch(() => {
          this.$message.success("操作已取消");
        });
    },
  //获取申请列表
  async fetchApplicationList() {
      try {
        const response = await axios.get('/application/ApplicationList', {

          params: {
            clubId: this.selectedClub.clubId,
            getAll: false // 或者根据需求设置为 true
          }
        });
        if (response.data.code === 0) {
          console.log(response)
          this.applicationList = response.data.data;
        } else {
          ElMessage.error(response.data.message || '获取申请列表失败');
        }
      } catch (error) {
        console.error('Error fetching application list:', error);
        ElMessage.error('获取申请列表失败，请重试');
      }
    },
    async approveJoinRequest(id) {
      await this.handleApplication(id, true);
    },

    async rejectJoinRequest(id) {
      await this.handleApplication(id, false);
    },

    async handleApplication(applicationId, approve) {
      try {
        const response = await axios.post('/application/approveClub', null, {
          params: {
            applicationId: applicationId,
            approve: approve
          }
        });

        if (response.data.code === 0) {
          ElMessage.success(approve ? '申请已批准' : '申请已驳回');
          this.fetchApplicationList(); // 重新获取列表以更新数据
        } else {
          ElMessage.error(response.data.message || '操作失败');
        }
      } catch (error) {
        console.error('Error handling application:', error);
        ElMessage.error('操作失败，请重试');
      }
    },
  },
  mounted() {
    this.fetchApplicationList();
  },
  watch: {
    selectedClub() {
      this.fetchApplicationList();
    }
  },

};
</script>

<style scoped>
.main-content {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 10px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

h3.club-name {
  font-family: 'ZCOOL KuaiLe', cursive;
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 20px;
  text-align: center;
  color: #d23f31;
}

.el-link.club-link {
  font-size: 28px;
  text-decoration: none;
  color: #d23f31;
  transition: all 0.3s ease;
}

.el-link.club-link:hover {
  color: #ff6b6b;
}


.btn-join-approval {
  background-color: #ff26269e; /* 浅橙色 */
  color: white;
  border: none;
  border-radius: 20px;
  font-weight: bold;
  transition: all 0.3s ease;
}

.btn-join-approval:hover {
  background-color: #ff2663d5; /* 深橙色 */
}

.btn-admin-manager {
  background-color: #ff914d; /* 浅橙色 */
  color: white;
  border: none;
  border-radius: 20px;
  font-weight: bold;
  transition: all 0.3s ease;
}

.btn-admin-manager:hover {
  background-color: #f57c00; /* 深橙色 */
}

.btn-edit-info {
  background-color: #fea463; /* 浅橙色 */
  color: white;
  border: none;
  border-radius: 20px;
  font-weight: bold;
  transition: all 0.3s ease;
}

.btn-edit-info:hover {
  background-color: #ef6c00; /* 深橙色 */
}

.btn-edit-logo {
  background-color: #f98077; /* 浅橙色 */
  color: white;
  border: none;
  border-radius: 20px;
  font-weight: bold;
  transition: all 0.3s ease;
}

.btn-edit-logo:hover {
  background-color: #ff5e3d;
}

.btn-disband-club {
  background-color: #ff4000;
  color: white;
  border: none;
  border-radius: 20px;
  font-weight: bold;
  transition: all 0.3s ease;
}

.btn-disband-club:hover {
  background-color: #d80d0d;
}

.el-divider {
  margin: 20px 0;
}

.dialog-footer {
  /* text-align: center; */
  padding: 10px 0;
}

.el-dialog {
  border-radius: 10px;
}

.el-dialog__header {
  background-color: #f56c6c;
  color: white;
  border-top-left-radius: 10px;
  border-top-right-radius: 10px;
}

.el-dialog__body {
  padding: 20px;
}

.el-dialog__footer {
  background-color: #f9f9f9;
  border-bottom-left-radius: 10px;
  border-bottom-right-radius: 10px;
}

.el-table {
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.el-table th {
  background-color: #f56c6c;
  color: white;
  text-align: center;
}

.el-table td {
  text-align: center;
}

.el-select {
  width: 150px;
  border-radius: 10px;
}
.mx-1{
  font-family: 'ZCOOL KuaiLe', cursive;
  font-size: 24px;
  margin-bottom: 20px;
  text-align: center;
  color: #d23f31;
  font-weight: 300; /* 尝试降低字体粗细 */
}
</style>
